package com.xiyu.service.service.material;

import com.xiyu.service.vo.material.stock.StockSingleGetByDetailInput;
import com.xiyu.service.vo.material.stock.StockSingleGetByDetailOutput;
import com.xiyu.service.vo.material.stock.StockGetListByDetailOutput;
import com.xiyu.service.vo.material.stock.StockGetListByDetailInput;
import com.xiyu.service.model.material.stock.MaterialStockDetail;
import com.xiyu.service.repository.material.stock.MaterialStockDetailRepository;
import com.xiyu.service.vo.material.stock.StockPageQueryOutput;
import com.xiyu.service.vo.material.stock.StockPageQueryInput;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.babyfish.jimmer.Page;
import java.util.*;

import com.xiyu.service.framework.web.web.core.pojo.PageResult;
import com.xiyu.service.convert.material.StockConvert;

import static com.xiyu.service.framework.exception.util.ServiceExceptionUtil.exception;

/**
 * 库存管理 Service 实现类
 */
@Service
@Validated
public class StockServiceImpl implements StockService {

    @Resource
    private MaterialStockDetailRepository materialStockDetailRepository;


    @Override
    public PageResult<StockPageQueryOutput> pageQuery(StockPageQueryInput inputVO) {
        Page<MaterialStockDetail> pageMaterialStockDetail = materialStockDetailRepository.pageQuery(inputVO);
        List<StockPageQueryOutput> listMaterialStockDetail = StockConvert.INSTANCE.pageQueryOutputConvert(pageMaterialStockDetail.getRows());
        return new PageResult<>(listMaterialStockDetail, pageMaterialStockDetail.getTotalRowCount());
    }

    @Override
    public List<StockGetListByDetailOutput> getListByDetail(List<StockGetListByDetailInput> inputVO) {
        List<MaterialStockDetail> stockDetails = new ArrayList<>();
        for(StockGetListByDetailInput input: inputVO){
            Optional<MaterialStockDetail> optionalMaterialStockDetail = materialStockDetailRepository.findByUniqueColumn(
                    input.getWarehouseId(), input.getMaterialId(), input.getBatchNo(), input.getProductionDate(),
                    input.getExpireDate()
            );
            if(optionalMaterialStockDetail.isPresent())
                stockDetails.add(optionalMaterialStockDetail.get());
            else
                stockDetails.add(null);
        }
        return StockConvert.INSTANCE.getListByDetailOutputConvert(stockDetails);
    }

    @Override
    public StockSingleGetByDetailOutput singleGetByDetail(StockSingleGetByDetailInput inputVO) {
        Optional<MaterialStockDetail> optionMaterialStockDetail = materialStockDetailRepository.findByUniqueColumn(
                inputVO.getWarehouseId(), inputVO.getMaterialId(), inputVO.getBatchNo(), inputVO.getProductionDate(),
                inputVO.getExpireDate()
        );
        return optionMaterialStockDetail.map(StockConvert.INSTANCE::singleGetByDetailOutputConvert).orElse(null);

    }

}
